<template>
  <div class="container p-6">
    <!-- 搜索区域 -->
    <div class="mb-4 flex items-center space-x-4">
      <el-input
        v-model="searchParams.Name"
        placeholder="输入学生姓名"
        class="!w-[200px]"
        clearable
        @input="handleAutoSearch"
        @clear="handleAutoSearch"
        size="large"
      />
      <el-select
        v-model="searchParams.gradeId"
        placeholder="选择班级"
        class="!w-[200px]"
        filterable
        clearable
        @change="handleAutoSearch"
        size="large"
      >
        <el-option
          v-for="item in classList"
          :key="item.id"
          :label="item.gradeName"
          :value="item.id"
        />
      </el-select>
      <el-select
        v-model="searchParams.examId"
        placeholder="选择考试"
        class="!w-[200px]"
        filterable
        clearable
        @change="handleAutoSearch"
        size="large"
      >
        <el-option
          v-for="item in examList"
          :key="item.id"
          :label="item.title"
          :value="item.id"
        />
      </el-select>
      <el-button type="primary" @click="handleSearch" size="large"
        >查询</el-button
      >
      <el-button @click="resetSearch" size="large">重置</el-button>
    </div>

    <!-- 表格区域 -->
    <el-table v-loading="loading" :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="序号" width="80" align="center" />
      <el-table-column
        prop="name"
        label="学生姓名"
        width="120"
        align="center"
      />
      <el-table-column
        prop="title"
        label="考试名称"
        min-width="180"
        align="center"
      />
      <el-table-column prop="score" label="分数" width="100" align="center">
        <template #default="scope">
          <span>{{ scope.row.userScore }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag
            :type="
              scope.row.score >= scope.row.passedScore ? 'success' : 'danger'
            "
          >
            {{ scope.row.score >= scope.row.passedScore ? '及格' : '不及格' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="limitTime"
        label="考试时间"
        min-width="180"
        align="center"
      />
      <el-table-column prop="userTime" label="用时" width="180" align="center">
        <template #default="scope">
          <span>{{ formatTime(scope.row.userTime) }}</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="mt-4 flex items-center text-sm text-gray-500">
      <span>共 {{ searchParams.total }} 条</span>
      <div class="ml-4 flex items-center">
        <el-select
          v-model="searchParams.pageSize"
          class="!w-[100px] mr-2"
          @change="handleSizeChange"
        >
          <el-option
            v-for="size in [10, 20, 30, 50]"
            :key="size"
            :label="`${size}条/页`"
            :value="size"
          />
        </el-select>
        <el-pagination
          v-model:current-page="searchParams.pageNum"
          :page-size="searchParams.pageSize"
          layout="prev, pager, next"
          :total="searchParams.total"
          :pager-count="5"
          background
          @current-change="handleCurrentChange"
        />
        <span class="mx-2">前往</span>
        <el-input
          v-model="jumpPage"
          class="!w-[50px]"
          @keyup.enter="handleJumpPage"
        />
        <span class="mx-2">页</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { getScoreList } from '@/api/teacher/score'
import { getGradelist } from '@/api/teacher/classmanage'
import { getExamlist } from '@/api/teacher/exam'

const router = useRouter()

// 表格数据
const tableData = ref([])
const loading = ref(false)
const classList = ref([])
const examList = ref([])

// 分页相关
const searchParams = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
  name: '',
  gradeId: '',
  examId: '',
})

// 跳转页码
const jumpPage = ref('')

// 获取班级列表
const getGradeList = async () => {
  try {
    const { data } = await getGradelist()
    classList.value = data.records
    // 设置默认班级ID
  } catch (error) {
    console.error('获取班级列表失败:', error)
    ElMessage.error('获取班级列表失败')
  }
}

// 获取考试列表
const getExamList = async () => {
  try {
    const { data } = await getExamlist()
    examList.value = data.records
    // 设置默认考试ID
    if (data.records && data.records.length > 0) {
      searchParams.examId = data.records[0].id
    }
  } catch (error) {
    console.error('获取考试列表失败:', error)
    ElMessage.error('获取考试列表失败')
  }
}

// 获取成绩列表
const getScoresList = async () => {
  if (loading.value) return
  loading.value = true
  try {
    console.log('发送请求参数:', searchParams)
    const { data } = await getScoreList({
      pageNum: searchParams.pageNum,
      pageSize: searchParams.pageSize,
      name: searchParams.name || undefined,
      gradeId: searchParams.gradeId || undefined,
      examId: searchParams.examId || undefined,
    })
    tableData.value = data.records
    searchParams.total = data.total
    searchParams.pageNum = data.current

    loading.value = false
  } catch (error) {
    console.error('获取成绩列表失败:', error)
    ElMessage.error('获取成绩列表失败')
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  searchParams.pageNum = 1
  getScoresList()
}

// 重置搜索
const resetSearch = () => {
  searchParams.Name = ''
  searchParams.gradeId = ''
  searchParams.examId = ''
  searchParams.pageNum = 1
  getScoresList()
}

// 自动搜索（防抖）
let searchTimer = null
const handleAutoSearch = () => {
  if (searchTimer) {
    clearTimeout(searchTimer)
  }
  searchTimer = setTimeout(() => {
    handleSearch()
  }, 500)
}

// 查看详情
const handleViewDetail = (row) => {
  ElMessage.info(
    `查看学生"${row.studentName}"的成绩详情，考试: ${row.examTitle}`
  )
  // 此处可以添加路由跳转到详情页面
  // router.push(`/teacher/score/detail?id=${row.id}`)
}

// 处理每页显示数量变化
const handleSizeChange = (val) => {
  searchParams.pageSize = val
  getScoresList()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  searchParams.pageNum = val
  getScoresList()
}

// 处理跳转页码
const handleJumpPage = () => {
  const page = Number(jumpPage.value)
  if (
    page &&
    page > 0 &&
    page <= Math.ceil(searchParams.total / searchParams.pageSize)
  ) {
    searchParams.pageNum = page
    getScoresList()
  } else {
    ElMessage.warning('请输入有效的页码')
  }
  jumpPage.value = ''
}

// 格式化用时为时分秒
const formatTime = (seconds) => {
  if (!seconds && seconds !== 0) return '--'

  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const remainingSeconds = seconds % 60

  // 补零函数
  const pad = (num) => (num < 10 ? '0' + num : num)

  // 始终使用完整格式，并添加单位
  if (hours > 0) {
    return `${hours}小时${pad(minutes)}分${pad(remainingSeconds)}秒`
  } else if (minutes > 0) {
    return `${minutes}分${pad(remainingSeconds)}秒`
  } else {
    return `${remainingSeconds}秒`
  }
}

// 页面加载时获取数据
onMounted(async () => {
  await getGradeList()
  await getExamList()
  await getScoresList()
})
</script>

<style lang="less" scoped>
.container {
  background-color: white;
  border-radius: 8px;
  min-height: calc(100vh - 120px);
}

:deep(.el-table) {
  .cell {
    display: flex;
    align-items: center;
    justify-content: center;
    white-space: nowrap;
  }

  .el-table__header th {
    .cell {
      justify-content: center;
    }
  }

  .el-button {
    margin: 0 auto;
  }
}

:deep(.el-pagination) {
  .el-pagination__total {
    margin-right: 16px;
  }

  .el-pagination__sizes {
    margin-right: 16px;
  }

  .el-pager li {
    background-color: transparent;

    &.is-active {
      background-color: var(--el-color-primary);
      color: white;
    }
  }

  .btn-prev,
  .btn-next {
    background-color: transparent;
  }

  .el-input__inner {
    text-align: center;
    padding: 0 5px;
  }
}

:deep(.el-select) {
  .el-input__wrapper {
    background-color: transparent;
  }
}
</style>
